<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .Bar {
            position: relative;
            width: 200px;
            /* 宽度 */
            border: 1px solid #B1D632;
            background: #fff;
            height: 20px;
            padding: 1px;
        }

        .Bar p {
            display: block;
            position: relative;
            /* 进度条背景颜色 */
            color: #333333;
            height: 20px;
            /* 高度 */
            line-height: 20px;
            /* 必须和高度一致，文本才能垂直居中 */
        }

        .Bar p span {
            position: absolute;
            top: -16px;
            width: 200px;
            background: peachpuff;
            /* 宽度 */
            text-align: center;
            /* font-weight: bold; */
           
        }
        
    </style>
    <script src="../jquery-3.4.1.js"></script>
</head>

<body>
    <form name="formname">
        <input type="file" name="file">
        <div class="Bar">
            <p> <span></span></p>

        </div>
    </form>
    <button>上传文件</button>
</body>
<script>
    let btn = document.querySelector('button');
    let _bar = document.querySelector('Bar');

    btn.onclick = () => {
        let data = new FormData(document.forms.namedItem('formname'));

        //创建了一个实例
        let xhr = new XMLHttpRequest;
        

        xhr.upload.onprogress = (e) => {
            //兼容问题（针对ie）
            e = e || window.event;
            let progress = (e.loaded / e.total * 100).toFixed(2) + '%';
            console.log("已上传" + progress);
            $('.Bar span').html(progress);
        }

        //open
        xhr.open('post', '../server/03-upload.php', true);
        //send
        xhr.send(data);

        //接收
        xhr.onload = () => {
            if (xhr.status == 200) {
                console.log('上传成功');
            }
        }
    }
</script>

</html>